# IIS 快速部署脚本（简化版）
# 使用方法: .\deploy-iis-quick.ps1

param(
    [string]$SiteName = "ScadaServiceManage",
    [int]$Port = 8080,
    [string]$BackendPath = "/api"
)

Write-Host "=====================================" -ForegroundColor Cyan
Write-Host "  SCADA服务管理器 - IIS快速部署" -ForegroundColor Cyan
Write-Host "=====================================" -ForegroundColor Cyan
Write-Host ""

# 检查管理员权限
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
    Write-Host "❌ 请以管理员身份运行此脚本！" -ForegroundColor Red
    exit 1
}

# 获取项目根目录
$ProjectRoot = $PSScriptRoot
$FrontendDist = Join-Path $ProjectRoot "dist"
$BackendDist = Join-Path $ProjectRoot "server\dist"

Write-Host "📦 步骤 1/5: 构建前端..." -ForegroundColor Yellow
Set-Location $ProjectRoot
npm run build
if ($LASTEXITCODE -ne 0) {
    Write-Host "❌ 前端构建失败！" -ForegroundColor Red
    exit 1
}
Write-Host "✅ 前端构建完成" -ForegroundColor Green

Write-Host ""
Write-Host "📦 步骤 2/5: 构建后端..." -ForegroundColor Yellow
Set-Location (Join-Path $ProjectRoot "server")
npm run build
if ($LASTEXITCODE -ne 0) {
    Write-Host "❌ 后端构建失败！" -ForegroundColor Red
    exit 1
}
Write-Host "✅ 后端构建完成" -ForegroundColor Green

Write-Host ""
Write-Host "🌐 步骤 3/5: 配置IIS站点..." -ForegroundColor Yellow

# 导入IIS模块
Import-Module WebAdministration -ErrorAction SilentlyContinue
if (-not (Get-Module WebAdministration)) {
    Write-Host "❌ IIS模块未安装！请先安装IIS。" -ForegroundColor Red
    exit 1
}

# 创建应用程序池
$PoolName = "${SiteName}Pool"
if (Test-Path "IIS:\AppPools\$PoolName") {
    Write-Host "  应用程序池已存在，正在重新配置..." -ForegroundColor Gray
    Remove-WebAppPool -Name $PoolName
}
New-WebAppPool -Name $PoolName
Set-ItemProperty "IIS:\AppPools\$PoolName" -Name "managedRuntimeVersion" -Value ""
Write-Host "  ✓ 应用程序池创建完成" -ForegroundColor Green

# 创建或更新网站
if (Test-Path "IIS:\Sites\$SiteName") {
    Write-Host "  网站已存在，正在更新..." -ForegroundColor Gray
    Stop-Website -Name $SiteName -ErrorAction SilentlyContinue
    Remove-Website -Name $SiteName
}

New-Website -Name $SiteName `
    -PhysicalPath $FrontendDist `
    -ApplicationPool $PoolName `
    -Port $Port

Write-Host "  ✓ 网站创建完成" -ForegroundColor Green

# 创建后端应用程序
$BackendAppName = "api"
if (Test-Path "IIS:\Sites\$SiteName\$BackendAppName") {
    Remove-WebApplication -Name $BackendAppName -Site $SiteName
}

New-WebApplication -Name $BackendAppName `
    -Site $SiteName `
    -PhysicalPath (Join-Path $ProjectRoot "server") `
    -ApplicationPool $PoolName

Write-Host "  ✓ 后端应用创建完成" -ForegroundColor Green

# 启用WebSocket
Set-WebConfigurationProperty -PSPath "IIS:\Sites\$SiteName" `
    -Filter "system.webServer/webSocket" `
    -Name "enabled" `
    -Value $true

Write-Host "  ✓ WebSocket已启用" -ForegroundColor Green

Write-Host ""
Write-Host "🔐 步骤 4/5: 配置权限..." -ForegroundColor Yellow

# 设置文件系统权限
$acl = Get-Acl $FrontendDist
$permission = "IIS_IUSRS", "ReadAndExecute", "ContainerInherit,ObjectInherit", "None", "Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
$acl.SetAccessRule($accessRule)
Set-Acl $FrontendDist $acl

$serverPath = Join-Path $ProjectRoot "server"
$acl = Get-Acl $serverPath
$acl.SetAccessRule($accessRule)
Set-Acl $serverPath $acl

Write-Host "  ✓ 权限配置完成" -ForegroundColor Green

Write-Host ""
Write-Host "🚀 步骤 5/5: 启动站点..." -ForegroundColor Yellow

Start-Website -Name $SiteName

# 等待站点启动
Start-Sleep -Seconds 2

$site = Get-Website -Name $SiteName
if ($site.State -eq "Started") {
    Write-Host "  ✓ 站点已启动" -ForegroundColor Green
} else {
    Write-Host "  ⚠ 站点启动可能有问题，请检查IIS日志" -ForegroundColor Yellow
}

Write-Host ""
Write-Host "=====================================" -ForegroundColor Cyan
Write-Host "✅ 部署完成！" -ForegroundColor Green
Write-Host "=====================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "访问地址: http://localhost:$Port" -ForegroundColor Cyan
Write-Host "后端API: http://localhost:$Port/api" -ForegroundColor Cyan
Write-Host ""
Write-Host "IIS管理器位置:" -ForegroundColor Gray
Write-Host "  - 站点: $SiteName" -ForegroundColor Gray
Write-Host "  - 应用程序池: $PoolName" -ForegroundColor Gray
Write-Host ""
Write-Host "日志位置:" -ForegroundColor Gray
Write-Host "  - 后端日志: $serverPath\iisnode" -ForegroundColor Gray
Write-Host ""
Write-Host "提示: 如果遇到问题，请检查:" -ForegroundColor Yellow
Write-Host "  1. IIS中是否安装了URL Rewrite模块" -ForegroundColor Yellow
Write-Host "  2. IIS中是否安装了iisnode模块" -ForegroundColor Yellow
Write-Host "  3. Node.js是否已安装（路径: %programfiles%\\nodejs\\node.exe）" -ForegroundColor Yellow
Write-Host "  4. 查看详细部署文档: IIS_DEPLOY.md" -ForegroundColor Yellow
Write-Host ""

# 询问是否打开浏览器
$openBrowser = Read-Host "是否现在打开浏览器? (Y/N)"
if ($openBrowser -eq "Y" -or $openBrowser -eq "y") {
    Start-Process "http://localhost:$Port"
}
